<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="30%"
    :close-on-click-modal="false"
    :before-close="handleClose">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm dialog-demo-ruleForm">
      <el-form-item label="事件名称" prop="name">
        <el-input size="small" v-model="ruleForm.name" placeholder="请输入事件名称"></el-input>
      </el-form-item>
      <el-form-item label="事件类型" prop="eventType">
        <el-select size="small" v-model="ruleForm.eventType" placeholder="请选择事件类型">
          <el-option label="地质灾害事件" value="1"></el-option>
          <el-option label="山洪灾害事件" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="事件等级" prop="level">
        <el-radio-group v-model="ruleForm.level" placeholder="请选择事件等级">
          <el-radio label="1" style="color:rgb(163, 179, 190)">重大事件</el-radio>
          <el-radio label="2" style="color:rgb(163, 179, 190)">一般事件</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="发生时间" prop="occurTime">
        <el-date-picker
          v-model="ruleForm.occurTime"
          type="datetime"
          size="small"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择发生时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="发生位置" required>
        <el-col :span="11">
          <el-form-item prop="locationType" style="width:95%">
            <el-select size="small" v-model="ruleForm.locationType" placeholder="请选择发生位置" @change="($event)=>selectChange($event,'search')">
              <el-option label="地质灾害隐患点" value="1"></el-option>
              <el-option label="山洪灾害隐患点" value="2"></el-option>
              <el-option label="自定义" value="3"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item prop="" style="width:95%">
            <el-select size="small" v-if="ruleForm.locationType !== '3'" v-model="ruleForm.location" placeholder="请选择发生位置" @change="locationClick">
              <el-option :label="item.name" :value="item.name" v-for="item,index in locationData" :key="index"></el-option>
            </el-select>
            <el-input v-model="ruleForm.coordString" v-else size="small" placeholder="请输入" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col class="line" :span="2" v-if="ruleForm.locationType === '3'">
          <img :src="img" alt="" srcset="" class="img"  @click="focusInput">
        </el-col>
      </el-form-item>
      <el-form-item label="报送单位" prop="submitUnit">
        <el-input size="small" placeholder="请输入报送单位" v-model="ruleForm.submitUnit"></el-input>
      </el-form-item>
      <el-form-item label="事件描述" prop="describe">
        <el-input size="small" placeholder="请输入事件描述" type="textarea" v-model="ruleForm.describe"></el-input>
      </el-form-item>
    </el-form>
    <el-dialog
      title="地图"
      :visible.sync="isShowMap"
      width="60%"
      class="mapDialog"
      :close-on-click-modal="false"
      :before-close="getCoordinate"
      append-to-body>
      <div class="search-input">
        <el-select
          v-model="value1"
          class="m-2"
          placeholder="请选择区县"
          size="small"
          style="margin-right: 0.1rem"
          @change="selectChanges"
          clearable
        >
          <el-option
            v-for="item in options1"
            :key="item.adcode"
            :label="item.areaName"
            :value="item.adcode"
          />
        </el-select>
        <el-select
          v-model="value2"
          class="m-2"
          placeholder="请选择乡镇"
          size="small"
          clearable
          @change="selectChangeRegion"
        >
          <el-option
            v-for="item in options2"
            :key="item.adcode"
            :label="item.areaName"
            :value="item.adcode"
          />
        </el-select>
        <span class="text">经度：</span><el-input class="input-lonLat" placeholder="请输入经度(-180 - 180)" size="small" v-model.number="lon"></el-input>
        <span class="text">纬度：</span><el-input class="input-lonLat" placeholder="请输入纬度(-90 - 90)" size="small" v-model.number="lat"></el-input>
        <el-button type="primary" class="inputbtn btn-inputbtn" icon="el-icon-search" @click="searchPoint"></el-button>
      </div>
      <div v-if="isShowMap" class="main" id="eventMap" ></div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="getCoordinate">确 定</el-button>
      </span>
    </el-dialog>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose" size="small">取 消</el-button>
      <el-button type="primary" @click="save" size="small">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import * as API from '../../api/emergency/index'
import * as resourceAPI from '../../api/dataResource/index'
import 'ol/ol.css'
import XYZ from 'ol/source/XYZ'
import { Map, View } from 'ol'
import { Tile } from 'ol/layer'
import { defaults as defaultControls } from 'ol/control'

import { Vector as VectorSource } from 'ol/source'
import { Vector as VectorLayer } from 'ol/layer'
import { Style, Icon } from 'ol/style'
import Feature from 'ol/Feature'
import Point from 'ol/geom/Point'
export default {
  props: {
    addEventDialog: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ''
    },
    rowData: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      options1: [],
      options2: [],
      geomText: null,
      value1: '',
      value2: '',
      lon: '',
      lat: '',
      locationData: [],
      coordinate: [],
      isShowMap: false,
      img: require('@/assets/mapView/sign.png'),
      visible: this.addEventDialog,
      ruleForm: {
        name: null,
        eventType: null,
        level: '1',
        occurTime: null,
        locationType: null,
        location: null,
        submitUnit: null,
        describe: null,
        coordString: null
      },
      rules: {
        name: [
          { required: true, message: '请输入事件名称', trigger: 'blur' }
        ],
        eventType: [
          { required: true, message: '请选择事件类型', trigger: 'change' }
        ],
        level: [
          { required: true, message: '请选择事件等级', trigger: 'change' }
        ],
        occurTime: [
          { required: true, message: '请选择发生时间', trigger: 'change' }
        ],
        locationType: [
          { required: true, message: '请选择发生位置', trigger: 'change' }
        ]
        // location: [
        //   { required: true, message: '请选择发生位置', trigger: 'change' }
        // ]
        // describe: [
        //   { required: true, message: '请输入事件描述', trigger: 'blur' }
        // ]
      },
      map: null
    }
  },
  mounted() {
    if (this.title === '编辑事件') {
      this.getEventById()
    }
    this.getAreaPage('options1', 3)
  },
  methods: {
    selectChanges(val) {
      this.value2 = ''
      this.geomText = this.options1.filter(item => item.adcode === val)
      if (this.geomText[0].centerLng && this.geomText[0].centerLat) {
        const JDWD = [Number(this.geomText[0].centerLng), Number(this.geomText[0].centerLat)]
        this.lon = this.geomText[0].centerLng
        this.lat = this.geomText[0].centerLat
        this.ruleForm.coordString = this.geomText[0].centerLng + ',' + this.geomText[0].centerLat
        this.clearMapPointLayers('focusInput')
        this.flyPoint(JDWD, 10)
        this.addPointInMap(JDWD, { img: this.img }, 'focusInput')
      } else {
        this.clearMapPointLayers('focusInput')
        this.lon = ''
        this.lat = ''
        this.ruleForm.coordString = null
      }
      this.getAreaPage('options2', 4, val)
    },
    selectChangeRegion(val) {
      this.geomText = this.options2.filter(item => item.adcode === val)
      if(this.geomText[0].centerLng&&this.geomText[0].centerLat){
        const JDWD = [Number(this.geomText[0].centerLng), Number(this.geomText[0].centerLat)]
        console.log(this.geomText, 'this.geomText')
        this.lon = this.geomText[0].centerLng
        this.lat = this.geomText[0].centerLat
        this.ruleForm.coordString = this.geomText[0].centerLng + ',' + this.geomText[0].centerLat
        this.clearMapPointLayers('focusInput')
        this.flyPoint(JDWD, 10)
        this.addPointInMap(JDWD, { img: this.img }, 'focusInput')
      } else {
        this.clearMapPointLayers('focusInput')
        this.lon = ''
        this.lat = ''
        this.ruleForm.coordString = null
      }
    },
    searchPoint(){
      if (this.lon && this.lat) {
        let lengLon =
          /^(\-|\+)?(((\d|[1-9]\d|1[0-7]\d|0{1,3})\.\d{0,100})|(\d|[1-9]\d|1[0-7]\d|0{1,3})|180\.0{0,6}|180)$/;
        let lengLat =
          /^-?((0|[1-8]?[0-9]?)(([.][0-9]{1,140})?)|90(([.][0]{1,140})?))$/;
        if (!lengLon.test(this.lon)) {
          return this.$message.error('经度格式不正确,-180至180')
        } else if (!lengLat.test(this.lat)) {
          return this.$message.error('纬度格式不正确,-90至90')
        }
        const JDWD = [this.lon, this.lat]
        this.clearMapPointLayers('focusInput')
        this.flyPoint(JDWD, 10)
        this.addPointInMap(JDWD, { img: this.img }, 'focusInput')
      }
    },
    getAreaPage(listName, level, val) {
      const params = {
        level: level,
        padcode: val
      }
      resourceAPI.areaPage(params).then((res) => {
        if (res.code === 200) {
          this[listName] = res.data
        }
      })
    },
    selectChange(val, name) {
      if (name === 'search') {
        this.ruleForm.location = null
      }
      this.ruleForm.coordString = null
      this.getHazardPointNames(val)
    },
    getHazardPointNames(val) {
      if (val !== '3') {
        const params = {
          eventType: val
        }
        API.getHazardPointNames(params).then(res => {
          if (res.code === 200) {
            this.locationData = res.data
          }
        })
      }
    },
    // 详情
    getEventById() {
      API.getEventById(this.rowData.id).then(res => {
        if (res.code === 200) {
          this.ruleForm = { ...res.data }
          this.selectChange(res.data.locationType, 'details')
        }
      })
    },
    handleClose() {
      this.$refs.ruleForm.resetFields()
      this.clearMapPointLayers('focusInput')
      this.$emit('handleClose')
    },
    save() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          if (this.ruleForm.locationType === '3' && !this.ruleForm.coordString) {
            this.$message.warning('请标注坐标位置!!!')
            return false
          }
          const data = {
            ...this.ruleForm
          }
          if (this.title === '新增事件') {
            API.commandAddEvent(data).then(res => {
              if (res.code === 200) {
                this.handleClose()
                this.$message.success(res.msg)
              }
            })
          } else {
            data.id = this.ruleForm.id
            API.getUpdateEvent(data).then(res => {
              if (res.code === 200) {
                this.handleClose()
                this.$message.success(res.msg)
              }
            })
          }
        }
      })
    },
    focusInput() {
      this.isShowMap = true
      this.$nextTick(() => {
        this.initMap('eventMap')
        if (this.title === '编辑事件') {
          const coordinate = JSON.parse(this.ruleForm.geojson)
          this.clearMapPointLayers('focusInput')
          this.addPointInMap(coordinate.coordinates, { img: this.img }, 'focusInput')
        }
        this.map.on('click', (e) => {
          this.value1 = ''
          this.value2 = ''
          this.clearMapPointLayers('focusInput')
          this.addPointInMap(e.coordinate, { img: this.img }, 'focusInput')
          this.coordinate = e.coordinate
          this.lon = e.coordinate[0]
          this.lat = e.coordinate[1]
          this.ruleForm.coordString = e.coordinate[0] + ',' + e.coordinate[1]
        })
      })
    },
    getCoordinate() {
      this.isShowMap = false
      this.value1 = ''
      this.value2 = ''
      this.lon = ''
      this.lat = ''
    },
    // 发生位置
    locationClick(val) {
      const arr = this.locationData.filter(item=>item.name === val)
      this.ruleForm.coordString = JSON.parse(arr[0].geojson).coordinates[0] + ',' + JSON.parse(arr[0].geojson).coordinates[1]
    },
    // 加点
    addPointInMap(coordinates, data, id) {
      const layers = this.map.getLayers().getArray()
      let layer = layers.find((item) => item.values_.id === id)
      if (layer) {
        layer.getSource().clear()
      } else {
        layer = new VectorLayer({
          source: new VectorSource(),
          properties: {
            id: id
          }
        })
        this.map.addLayer(layer)
      }
      const imgUrl = data['img'] ? data['img'] : require('../../assets/mapView/sign.png')
      // 创建矢量对象
      const feature = new Feature({
        geometry: new Point(coordinates),
        properties: data
      })
      feature.setStyle(
        new Style({
          image: new Icon({
            anchor: [16, 32],
            anchorXUnits: 'pixels',
            anchorYUnits: 'pixels',
            src: imgUrl
          })
        })
      )
      // 添加到之前的创建的layer中去
      layer.getSource().addFeature(feature)
    },
    // 删除点
    clearMapPointLayers(id) {
      if (this.map) {
        const lys = this.map.getLayers().getArray()
        const len = lys.length - 1
        for (let i = len; i > 0; i--) {
          if (lys[i].values_.id === id) {
            lys[i].getSource().clear()
            this.map.removeOverlay(lys[i])
          }
        }
      }
    },
    // 初始化地图
    initMap(target, options = {}, config = { r: true }) {
      const KEY = 'd0c45508c851842ea4e34ec56780348c'
      const tianDiTu = {
        // 矢量
        vector: `https://t${Math.round(Math.random() * 7)}.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=${KEY}`,
        vectorMark: 'http://t' + Math.round(Math.random() * 7) + '.tianditu.gov.cn/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=' + KEY,
        // 影像
        raster: 'http://t' + Math.round(Math.random() * 7) + '.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=' + KEY,
        rasterMark: 'http://t' + Math.round(Math.random() * 7) + '.tianditu.gov.cn/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=' + KEY,
        // 地形
        topography: 'http://t' + Math.round(Math.random() * 7) + '.tianditu.gov.cn/DataServer?T=ter_w&x={x}&y={y}&l={z}&tk=' + KEY,
        topographyMark: 'http://t' + Math.round(Math.random() * 7) + '.tianditu.gov.cn/DataServer?T=cta_w&x={x}&y={y}&l={z}&tk=' + KEY
      }
      const tileUrlFunction = function(xyz) {
        const z = xyz[0]
        const x = xyz[1]
        const y = xyz[2]
        return `https://rt1.map.gtimg.com/realtimerender?z=${z}&x=${x}&y=${y}&type=vector&style=0&key=KSMBZ-3SMCV-LTYPU-UPYHY-GI2WF-UWBXB`
      }
      const crtlayerXYZ = function(id, url, visible, tileUrlFunction = function() { }) {
        return new Tile({
          source: new XYZ({
            url,
            crossOrigin: 'anonymous',
            tileUrlFunction
          }),
          properties: {
            layerId: 'TileLayers'
          },
          visible,
          id
        })
      }
      this.map = new Map({
        layers: [
          // 矢量
          crtlayerXYZ('VECTOR', tianDiTu.vector, !!config.v, tileUrlFunction),
          crtlayerXYZ('VECTORMARK', tianDiTu.vectorMark, !!config.v, tileUrlFunction),
          // 影像
          crtlayerXYZ('RASTER', tianDiTu.raster, !!config.r, tileUrlFunction),
          crtlayerXYZ('RASTERMARK', tianDiTu.rasterMark, !!config.r, tileUrlFunction),
          // 地形
          crtlayerXYZ('TOPOGRAPHY', tianDiTu.topography, !!config.t, tileUrlFunction),
          crtlayerXYZ('TOPOGRAPHYMARK', tianDiTu.topographyMark, !!config.t, tileUrlFunction)
        ],
        target: target,
        view: new View({
          projection: 'EPSG:4326',
          center: [100.871785, 36.959049],
          zoom: 6,
          maxZoom: 18,
          ...options
        }),
        controls: defaultControls({
          zoom: false,
          rotate: false,
          attribution: false
        })
      })
    },
    flyPoint(JDWD, zoom) {
      this.map.getView().animate({
        center: JDWD,
        zoom: zoom || 6,
        duration: 1800 // 飞行时间
      })
    },
  },

  destroyed() {
    if (this.map) {
      // 存在旧地图实例
      this.map.getView().setZoom(0) // 将缩放级别设置为 0
      this.map.setTarget(null) // 解除 DOM 元素的绑定
      this.map.dispose() // 销毁地图实例
      // 可能需要根据 mapOl 的文档调用相应的销毁方法
      // this.map.destroy()
      this.map = null
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog-demo-ruleForm{
  :deep(.el-form-item){
    width: 90%;
    .el-select{
      width: 100%;
    }
    .el-date-editor{
      width: 100%;
    }
  }
  .img{
    width: 28px;
    height: 28px;
    vertical-align: middle;
    cursor: pointer;
  }
}
.mapDialog{
  :deep(.el-dialog__body){
    height: 500px;
  }
}
:deep(.el-dialog){
  background: rgba(3,27,54,0.7);
}
:deep(.el-dialog__title){
  color: #fff;
}
:deep(.el-textarea__inner){
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255,255,255,0.2);
  color: #fff;
  font-family: none;
}

:deep(.el-input__inner) {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 6px 6px 6px 6px;
  opacity: 1;
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: rgba(255, 255, 255, 1);
}

:deep(.el-input-group__append) {
  background: none;
  border: none;
  color: #fff;
  font-size: 20px;
  width: 40px;
  height: 40px;
  padding: 0px;
}
.search-input {
  background: linear-gradient(90deg, #031b36 0%, rgba(3, 28, 51, 0.3) 100%);
  box-shadow: 0px 4px 6px 0px rgba(0, 0, 0, 0.5);
  width: 100%;
  height: 40px;
  display: flex;
  align-items: center;
  margin-bottom: 0.1rem;
  justify-content: space-between;
  .m-2{
    width: 30%;
  }
  .text{
    width: 7%;
    text-align: right;
    color: #fff;
  }
  .input-lonLat{
    width: 30%;
  }
  :deep(.el-input__inner) {
    color: #fff;
    font-size: 14px;
    height: 40px;
    // background: linear-gradient(180deg, #000000 0%, rgba(0, 0, 0, 0.8) 100%);
  }
}
.inputbtn {
  background: linear-gradient(135deg, #2270d4 0%, #002689 100%);
  border-radius: 0px 4px 4px 0px;
  width: 40px;
  height: 40px;
  text-align: center;
  line-height: 40px;
}
.btn-inputbtn{
  width: auto;
  text-align: unset;
  line-height: unset;
}
.main{
  width:100%;
  height:calc(100% - 0.5rem)
}
</style>
